package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"nspel/entity"
	"nspel/model"
	"nspel/nspel"
	"nspel/util"
	"strconv"
	"time"
)

type LabelManageController struct {
	beego.Controller
}

func (c *LabelManageController) PostValidateLabel() {
	defer c.ServeJSON()
	req := model.PostValidateLabelReq{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	if req.Name == "" || req.Color == "" {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	if req.Color != "primary" && req.Color != "success" && req.Color != "info" && req.Color != "warning" && req.Color != "danger" {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	label := new(entity.Label)
	err = label.SelectAllByValueColor(req.Name, req.Color)
	if err != nil {
		if err == orm.ErrNoRows {
			c.Data["json"] = map[string]interface{}{"retCode": 0, "result": true}
			return
		} else {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
	} else {
		if label.Id != req.Id {
			c.Data["json"] = map[string]interface{}{"retCode": 0, "result": false, "msg": "存在重复名称颜色的标签"}
		} else {
			c.Data["json"] = map[string]interface{}{"retCode": 0, "result": true}
		}
		return
	}
}

func (c *LabelManageController) PostLabelAdd() {
	defer c.ServeJSON()
	req := model.PostLabelAddReq{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	if req.Value == "" || req.Color == "" {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	if req.Color != "primary" && req.Color != "success" && req.Color != "info" && req.Color != "warning" && req.Color != "danger" {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	label := new(entity.Label)
	err = label.SelectAllByValueColor(req.Value, req.Color)
	if err != nil {
		if err == orm.ErrNoRows {
			label.Value = req.Value
			label.Color = req.Color
			err = label.Insert()
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
			c.Data["json"] = map[string]interface{}{"retCode": 0, "msg": "新增成功"}
			nspel.RedisKeyDelete("label")
			return
		} else {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
	} else {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
}

func (c *LabelManageController) GetLabelList() {
	defer c.ServeJSON()
	req := model.GetLabelListReq{}
	b := req.Validate("page-size", "current-page", &c.Controller)
	if !b {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	if req.PageSize < 0 || req.CurrentPage < 0 {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	res := model.GetLabelListRes{RetCode: 0}
	label := new(entity.Label)
	hashKey := "pageSize[" + strconv.FormatInt(req.PageSize, 10) + "].currentPage[" + strconv.FormatInt(req.CurrentPage, 10) + "]"
	offset := (req.CurrentPage - 1) * req.PageSize
	ormEng := nspel.GetOrmEngine().QueryTable(label.TableName()).Limit(req.PageSize, offset)
	count, err := label.Count()
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	res.Total = count
	labels, err := label.CustomSelect(&ormEng, hashKey)
	res.Data = make([]model.LabelList, len(labels))
	for i := 0; i < len(labels); i++ {
		res.Data[i].Id = labels[i].Id
		res.Data[i].Index = offset + int64(i) + 1
		res.Data[i].Value = labels[i].Value
		res.Data[i].Color = labels[i].Color
	}
	c.Data["json"] = res
}

func (c *LabelManageController) PostLabelModify() {
	defer c.ServeJSON()
	req := model.PostLabelModifyReq{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	if req.Value == "" || req.Color == "" {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	if req.Color != "primary" && req.Color != "success" && req.Color != "info" && req.Color != "warning" && req.Color != "danger" {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	label := new(entity.Label)
	err = label.SelectAllById(req.Id)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	label.Value = req.Value
	label.Color = req.Color
	err = label.Update("value", "color")
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	nspel.RedisKeyDelete("label")
	c.Data["json"] = map[string]interface{}{"retCode": 0, "msg": "更新成功"}
}

func (c *LabelManageController) DeleteLabel() {
	defer c.ServeJSON()
	req := model.DeleteLabelReq{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	for i := 0; i < len(req.Id); i++ {
		label := new(entity.Label)
		err := label.SelectAllById(req.Id[i])
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
	}
	label := new(entity.Label)
	for i := 0; i < len(req.Id); i++ {
		err := label.DeleteById(req.Id[i])
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
	}
	nspel.RedisKeyDelete("label")
	c.Data["json"] = map[string]interface{}{"retCode": 0, "msg": "删除成功"}
}

func (c *LabelManageController) GetLabelTagList() {
	defer c.ServeJSON()
	authority, ok := c.Ctx.Input.Session("authority").(byte)
	if !ok {
		c.Data["json"] = model.ErrorRes{RetCode: 1, Msg: "session失效"}
		return
	}
	uid, ok := c.Ctx.Input.Session("uid").(int64)
	if !ok {
		c.Data["json"] = model.ErrorRes{RetCode: 1, Msg: "session失效"}
		return
	}
	res := model.GetLabelTagListRes{RetCode: 0}
	var count int64
	var err error
	var students []entity.Student
	if authority == entity.ManagerAuthority.Administrator {
		req := model.GetStudentsListAdmin{}
		b := req.Validate("province-id", "city-id", "area-id", "school-name", "join-year", "school-roll-id", "page-size", "current-page", &c.Controller)
		if !b {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
			return
		}
		count, students, err = util.GetStudentsListAdministrator(req.ProvinceId, req.CityId, req.AreaId, req.SchoolName, req.JoinYear, req.SchoolRollId, req.PageSize, req.CurrentPage)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		res.Total = int64(count)
	} else if authority == entity.ManagerAuthority.Area {
		req := model.GetStudentsListArea{}
		b := req.Validate("join-year", "school-id", "school-roll-id", "page-size", "current-page", &c.Controller)
		if !b {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
			return
		}
		area := new(entity.Area)
		err = area.SelectAllByUserId(uid)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		count, students, err = util.GetStudentsListArea(area.Id, req.JoinYear, req.SchoolId, req.SchoolRollId, req.PageSize, req.CurrentPage)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		res.Total = int64(count)
	} else if authority == entity.ManagerAuthority.School {
		req := model.GetStudentsListSchool{}
		b := req.Validate("school-roll-id", "page-size", "current-page", &c.Controller)
		if !b {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
			return
		}
		school := new(entity.School)
		err = school.SelectAllByUserId(uid)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		count, students, err = util.GetStudentsListSchool(school.Id, req.SchoolRollId, req.PageSize, req.CurrentPage)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		res.Total = int64(count)
	}
	res.Data = make([]model.LabelTagList, len(students))
	for i := 0; i < len(students); i++ {
		res.Data[i].Id = students[i].Id
		res.Data[i].SchoolRollId = students[i].SchoolRollId
		res.Data[i].Name = students[i].Name
		res.Data[i].Grade = util.GetGrade(students[i].CurrentGrade, students[i].CurrentClass)
		if students[i].CurrentClass[5:6] == "0" {
			res.Data[i].Class = students[i].CurrentClass[6:7]
		} else {
			res.Data[i].Class = students[i].CurrentClass[5:7]
		}
		school := new(entity.School)
		err = school.SelectAllById(students[i].SchoolId)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		res.Data[i].SchoolName = school.Name
		if !students[i].Birthday.IsZero() {
			res.Data[i].YearOld = strconv.Itoa(time.Now().Year() - students[i].Birthday.Year())
		}
		if students[i].Sex == 1 {
			res.Data[i].Sex = "男"
		} else if students[i].Sex == 2 {
			res.Data[i].Sex = "女"
		}
		score := new(entity.Score)
		err = score.SelectAllBySchoolRollIdLastestMeasurementDate(students[i].SchoolRollId)
		if err != nil && err != orm.ErrNoRows {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		res.Data[i].PhysicalTotalScore = score.PhysicalTotalScore.Float64
		tag := new(entity.Tag)
		tags, err := tag.SelectAllByStudentId(students[i].Id)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		res.Data[i].Label = make([]model.LabelList, len(tags))
		for j := 0; j < len(tags); j++ {
			label := new(entity.Label)
			err = label.SelectAllById(tags[j].LabelId)
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
			res.Data[i].Label[j].Id = label.Id
			res.Data[i].Label[j].Value = label.Value
			res.Data[i].Label[j].Color = label.Color
		}
	}
	c.Data["json"] = res
}

func (c *LabelManageController) PostLabelTag() {
	defer c.ServeJSON()
	req := model.PostLabelTagReq{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	for i := 0; i < len(req.Data); i++ {
		student := new(entity.Student)
		err = student.SelectAllById(req.Data[i].StudentId)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		label := new(entity.Label)
		for j := 0; j < len(req.Data[i].LabelId); j++ {
			err = label.SelectAllById(req.Data[i].LabelId[j])
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
		}
		tag := new(entity.Tag)
		for j := 0; j < len(req.Data[i].LabelId); j++ {
			err = tag.SelectAllByStudentIdLabelId(req.Data[i].StudentId, req.Data[i].LabelId[j])
			if err != nil && err != orm.ErrNoRows {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
			if err == nil {
				continue
			}
			tag.LabelId = req.Data[i].LabelId[j]
			tag.StudentId = req.Data[i].StudentId
			err = tag.Insert()
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
		}
	}
	defer nspel.RedisKeyDelete("tag")
	c.Data["json"] = map[string]interface{}{"retCode": 0, "msg": "插入成功"}
}

func (c *LabelManageController) DeleteLabelTag() {
	defer c.ServeJSON()
	req := model.PostLabelTagReq{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	for i := 0; i < len(req.Data); i++ {
		student := new(entity.Student)
		err = student.SelectAllById(req.Data[i].StudentId)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		label := new(entity.Label)
		for j := 0; j < len(req.Data[i].LabelId); j++ {
			err = label.SelectAllById(req.Data[i].LabelId[j])
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
		}
		tag := new(entity.Tag)
		for j := 0; j < len(req.Data[i].LabelId); j++ {
			err = tag.DeleteByStudentIdLabelId(req.Data[i].StudentId, req.Data[i].LabelId[j])
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
		}
	}
	defer nspel.RedisKeyDelete("tag")
	c.Data["json"] = map[string]interface{}{"retCode": 0, "msg": "删除成功"}
}
